package com.xidian.zhiancloud.service.workTicket;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xidian.zhiancloud.dao.syset.SysUserMapper;
import com.xidian.zhiancloud.dao.workTicket.FireFlowMapper;
import com.xidian.zhiancloud.dto.ResultDTO;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.model.syset.SysUser;
import com.xidian.zhiancloud.model.workTicket.FireFlow;
import com.xidian.zhiancloud.model.workTicket.FireTicket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class FireFlowService extends ServiceImpl<FireFlowMapper, FireFlow> implements IService<FireFlow> {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private FireFlowService fireFlowService;

    @Autowired
    private FireFlowMapper fireFlowMapper;

    /**
     *
     *
     * @param currentStep 当前所在步骤
     * @param fireTicket  当前作业票已实现内容
     * @return
     */
    public Integer updateCurrentStep(Integer currentStep, FireTicket fireTicket) {
        Boolean isFinishCurrentStep = false;        // 假设大步骤未完成
        switch (currentStep) {
            case 1:
                if (fireTicket.getIsCommit1() != null && fireTicket.getIsCommit1() == 1) isFinishCurrentStep = true; break;
            case 2:
                if ((fireTicket.getIsCommit2() != null && fireTicket.getIsCommit2() == 1) && (fireTicket.getIsCommit3() != null && fireTicket.getIsCommit3() == 1) &&
                        (fireTicket.getIsCommit4() != null && fireTicket.getIsCommit4() != null && fireTicket.getIsCommit4() == 1) && (fireTicket.getIsCommit5() == 1)) isFinishCurrentStep = true; break;
            case 3:
                if ((fireTicket.getIsCommit6() == 1) && (fireTicket.getIsCommit7() == 1) && (fireTicket.getIsCommit8() == 1)) isFinishCurrentStep = true; break;
            case 4:
                if (fireTicket.getIsCommit9() == 1) isFinishCurrentStep = true; break;
            case 5:
                if (fireTicket.getIsCommit10() == 1) isFinishCurrentStep = true; break;
            case 6:
                if (fireTicket.getIsCommit11() == 1) isFinishCurrentStep = true; break;
            case 7:
                if (fireTicket.getIsCommit12() == 1) isFinishCurrentStep = true; break;
            case 8:
                if (fireTicket.getIsCommit13() == 1) isFinishCurrentStep = true; break;
            case 9:
                if (fireTicket.getIsCommit14() == 1) isFinishCurrentStep = true; break;
            case 10:
                if (fireTicket.getFinishCheck1Sign() != null && fireTicket.getFinishCheck2Sign()!=null) isFinishCurrentStep = true; break;
//            case 11:
//                if (fireTicket.getIsCommit16() == 1) isFinishCurrentStep = true; break;
        }

        // isFinishCurrentStep为true，则完成该大步
        if (isFinishCurrentStep) {
            // 根据动火级别判断当前大步骤的跳转。仅涉及二级动火（2）与一级动火（1）。
            Integer workLevel = fireTicket.getWorkLevel();
            if (workLevel == 1 && fireTicket.getIsCommit12() == 1) {                // 一级动火，且一级审批已经结束，忽略一级动火审批人（7）和特殊动火审批人（8），当前大步骤跳转到动火前验票人（9）
                currentStep = 8;
            } else if (workLevel == 2 && fireTicket.getIsCommit11() == 1) {         // 二级动火，且动火初审审批已经结束，当前大步骤跳转到动火前验票人（9）
                currentStep = 8;
            }
            return ++currentStep;
        } else {                    // 小步骤未全部完成，则仍留在原来的大步骤中
            return currentStep;
        }
    }


    /**
     * 根据大步骤currentStep的id在t_fire_flow中获取相关小步骤id的List
     *
     * @param currentStep
     * @return
     */
    public List<Long> getSubIdsByCurrent(Long companyId, Integer currentStep) {
        List<Long> subIdList = new LinkedList<>();
        // companyId查找记录
        LambdaQueryWrapper<FireFlow> query = Wrappers.<FireFlow>lambdaQuery();
        query.eq(FireFlow::getCompanyId, companyId);
        List<FireFlow> fireFlows = fireFlowMapper.selectList(query);
        // 该公司中，通过currentStep字段，获取当前大步骤下的所有小步骤的ids
        fireFlows.forEach(subId -> {
//            Integer subIds = subId.getBelongId();
            if (currentStep == subId.getBelongId()) {
                subIdList.add(subId.getId());
            }
        });
        return subIdList;
    }


    /**
     * 根据fireTicket的isCommit**字段判断哪一个小步骤完成提交。
     *
     * @param fireTicket
     * @return
     */
    public Integer getFinishSubId(Integer currentStep, FireTicket fireTicket) {
        Integer subStep = 0;                                                // 初始化subStep
        if (currentStep == 1)  subStep = 1;                                 // 当前在第一大步骤，则必在第1小步骤
        else if (currentStep == 2) {                                        // 第二大步骤有4个小步骤
            if (fireTicket.getFireAnalyse1Data() != null) subStep = 2;                // 选择第2小步骤中，代表性的字段，判断已完成 & 提交
            else if (fireTicket.getWorkerSign() != null ) subStep = 3;
            else if (fireTicket.getDanger1() != null) subStep = 4;
            else if (fireTicket.getDanger2() != null) subStep = 5;
        }
        else if (currentStep == 3) {
            if (fireTicket.getDependentSuperviseSign() != null) subStep = 6;
            if (fireTicket.getWorkSuperviseSign() != null) subStep = 7;
            if (fireTicket.getSafeEducationSign() != null) subStep = 8;
        }
        else if (currentStep == 4) subStep = 9;
        else if (currentStep == 5) subStep = 10;
        else if (currentStep == 6) subStep = 11;
        else if (currentStep == 7) subStep = 12;
        else if (currentStep == 8) subStep = 13;
        else if (currentStep == 9) subStep = 14;
        else if (currentStep == 10) subStep = 15;
        else if (currentStep == 11) subStep = 16;

        return subStep;
    }

    /**
     *
     *
     * @param analyseTime
     * @param nowTime
     * @return
     */
    public Boolean signOvertime(Date analyseTime, Date nowTime, Integer workLevel) {
        // getTime()方法返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数
        Boolean isOvertime = false;
        long startTime = analyseTime.getTime();
        long endTime = nowTime.getTime();
        // 时间间隔，单位为小时
        long timeInterval = endTime - startTime;
        double result = timeInterval * 1.0 / (1000 * 60 * 60);
        if (workLevel == 0 || workLevel == 1) {
            isOvertime =  result > 8.0 ? true : false;                  // 8小时超时
        } else if (workLevel == 2) {
            isOvertime =  result > 24.0 ? true : false;
        }
        return isOvertime;
    }

    /**
     * 返回工作流大步骤的{{人员}：{可编辑字段列表}}的映射关系
     *
     * @param currentStep 大步骤
     * @param subStepList 子步骤
     * @param companyId
     * @return
     */
    public List<Map<List<Long>, List<String>>> getEnableFieldMap(Long companyId, Integer currentStep, List<Long> subStepList) {
        // 定义返回值
        List<Map<List<Long>, List<String>>> operatorFieldList = new LinkedList<>();
        // 循环subStep.size()，即完成每一个小步骤
        for (int i = 0; i < subStepList.size(); i++) {
            List<Long> operatorIds = getOperatorIdsList(subStepList.get(i), companyId);
            List<String> enableField = getEnableFieldList(subStepList.get(i));
            // 新建Hash表，存储人员list与可编辑字段list
            Map<List<Long>, List<String>> operatorFieldMap = new HashMap<List<Long>, List<String>>();
            operatorFieldMap.put(operatorIds, enableField);
            operatorFieldList.add(operatorFieldMap);
        }

        return operatorFieldList;
    }

    /**
     * 根据当前步骤id返回具有操作权限人员的id的List
     *
     * @param flowId
     * @param companyId
     * @return
     */
    public List<Long> getOperatorIdsList(Long flowId, Long companyId) {
        // 根据id获取当前步骤的内容
        FireFlow fireFlow = fireFlowService.getById(flowId);
        // 获取人员筛选的ids
        String ids_s = fireFlow.getSelectPerson();
        // 通过选择标准进行筛选
        Integer selectStandard = fireFlow.getSelectStandard();
        List<Long> operatorIds = getPeopleIds(selectStandard, ids_s, companyId);
        return operatorIds;
    }

    /**
     * 根据当前步骤id返回可编辑字段list
     *
     * @param flowId
     * @return
     */
    public List<String> getEnableFieldList(Long flowId) {
        FireFlow fireFlow = fireFlowService.getById(flowId);
        String enableFieldStr = fireFlow.getEnableField();
        List<String> enableFields = new LinkedList<>();
        for (String enableField : enableFieldStr.split(",")) {
            enableFields.add(enableField);
        }
        return enableFields;
    }

    /**
     * 根据筛选条件获取对应流程的可编辑人员列表
     *
     * @param selectStandard
     * @param ids_s
     * @param companyId
     * @return
     */
    List<Long> getPeopleIds(Integer selectStandard, String ids_s, Long companyId) {
        String[] ids = ids_s.split(",");
        Map<String, Boolean> isIdExist = new HashMap<>();
        for (String id : ids) {
            isIdExist.put(id, Boolean.TRUE);
        }

        // 根据公司id的获取数据记录
        LambdaQueryWrapper<SysUser> query = Wrappers.<SysUser>lambdaQuery();
        query.eq(SysUser::getCompanyid, companyId);
        List<SysUser> sysUsers = sysUserMapper.selectList(query);

        List<Long> user_ids = new LinkedList<>();

        // 根据职位选择
        if (selectStandard == 0) {
            sysUsers.forEach(user -> {
                String[] jobIds = user.getJobids().split(",");
                for (String jobId : jobIds) {
                    if (isIdExist.get(jobId) != null) {
                        user_ids.add(user.getId());
                        break;
                    }
                }
            });
        }

//        // 根据角色选择
//        else if (selectStandard == 1) {
//            sysUsers.forEach(user -> {
//                String[] roleIds = user.getRoleids().split(",");
//                for (String roleId : roleIds) {
//                    if (isIdExist.get(roleId) != null) {
//                        user_ids.add(user.getId());
//                        break;
//                    }
//                }
//            });
//        }
//
//        // 根据岗位选择
//        else if (selectStandard == 2) {
//            sysUsers.forEach(user -> {
//                String[] departIds = user.getDepartids().split(",");
//                for (String departId : departIds) {
//                    if (isIdExist.get(departId) != null) {
//                        user_ids.add(user.getId());
//                        break;
//                    }
//                }
//            });
//
//        }
//
//        // 根据组织机构选择
//        else if (selectStandard == 3) {
//            sysUsers.forEach(user -> {
//                String[] orgIds = user.getOrgids().split(",");
//                for (String orgId : orgIds) {
//                    if (isIdExist.get(orgId) != null) {
//                        user_ids.add(user.getId());
//                        break;
//                    }
//                }
//            });
//        }

        // 根据人员id选择
        else if (selectStandard == 1) {
            sysUsers.forEach(user -> {
                Long userId = user.getId();
                    if (isIdExist.get(userId) != null) {
                        user_ids.add(user.getId());
                    }
            });
        }

        return user_ids;
    }

    /**
     * 根据subId，查找对应的t_fire的id
     *
     * @param companyId
     * @param subId
     * @return
     */
    public Long getFlowBySubId(Long companyId, Integer subId) {
        Long flowId = null;
        // 根据companyId查询fireFlow
        LambdaQueryWrapper<FireFlow> query = Wrappers.<FireFlow>lambdaQuery();
        query.eq(FireFlow::getCompanyId, companyId);
        List<FireFlow> fireFlows = fireFlowMapper.selectList(query);

        // 在初次筛选的fireFlow中，根据subId获取id
        for (int i = 0; i < fireFlows.size(); i++) {
            if (fireFlows.get(i).getSubId() == subId) {
                flowId = fireFlows.get(i).getId();
                break;
            }
        }

        return flowId;
    }


}
